package util

import "reflect"

// ==================
// util-abstract_list: list基础实现
// ==================

type AbstractList[E any] struct {
	list[E]
	AbstractCollection[E]
}

func NewAbstractList[E any]() AbstractList[E] {
	abstractCollection := NewAbstractCollection[E]()
	list := AbstractList[E]{}
	list.AbstractCollection = abstractCollection
	return list
}

// IndexOf index of element
func (receiver *AbstractList[E]) IndexOf(o interface{}) int {
	it := receiver.Iterator()
	index := -1
	if o == nil {
		for it.HasNext() {
			index++
			val := it.Next()
			if val == nil {
				return index
			}
		}
	} else {
		for it.HasNext() {
			index++
			val := it.Next()
			if &val == o || reflect.DeepEqual(o, val) {
				return index
			}
		}
	}
	return -1
}

// LastIndexOf index of element
func (receiver *AbstractList[E]) LastIndexOf(o interface{}) int {
	it := receiver.Iterator()
	index := -1
	last := false
	if o == nil {
		for it.HasNext() {
			index++
			val := it.Next()
			if val == nil {
				last = true
			}
		}
	} else {
		for it.HasNext() {
			index++
			val := it.Next()
			if &val == o || reflect.DeepEqual(o, val) {
				last = true
			}
		}
	}
	if last {
		return index
	} else {
		return -1
	}
}
